# -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
import os
import json
import requests
from config.config import ModelConfig

class ModelConnector(ABC):
    @abstractmethod
    def send_request(self, messages, verbose=False):
        pass
    

class ApiConnector(ModelConnector):
    DEFAULT_TOKEN = ModelConfig.TOKEN
    DEFAULT_URL = ModelConfig.API_BASE+"/chat/completions"
    DEFAULT_MODEL = ModelConfig.NAME
    def __init__(self, token=DEFAULT_TOKEN, url=DEFAULT_URL, model=DEFAULT_MODEL, system_message=None):
        """
        初始化 ApiConnector 类
        :param token: API 访问令牌
        :param url: API 访问 URL
        :param system_message: 系统消息内容
        """
        if system_message is None:
            system_message = {
                'role': 'system',
                'content': 'You are a helpful assistant.'
            }
        self.token = token
        self.url = url
        self.system_message = system_message
        self.model = model
        

    def send_request(self, messages, verbose=False):

        payload = {
        'model': self.model,
        'messages': [
            self.system_message,
            {
                'role': 'user',
                'content': messages
            }
        ]
    }
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer {}'.format(self.token)
        }
        response = requests.post(self.url, headers=headers, json=payload)
        if response.status_code != 200:
            if verbose: 
                print("Request failed with status code: {}".format(response.status_code))
                print(response.json())
            return None
        else:
            # 格式化输出 JSON 结果
            response_json = response.json()
            if verbose:
                pretty_json = json.dumps(response_json, indent=4, ensure_ascii=False)
                print(pretty_json)
            
            # Safely extract specific fields from the JSON response
            choices = response_json.get('choices', [])
            if choices and len(choices) > 0:
                message_content = choices[0].get('message', {}).get('content', None)
                reasoning_content = choices[0].get('message', {}).get('reasoning_content', None)
                return message_content
            else:
                if verbose:
                    print("No choices found in the response.")
                return None
if __name__ == "__main__":
    api_connector = ApiConnector()
    # test_messages = "Hello, how are you?"
    test_messages = """
Generate pseudocode for the algorithm described in the user's input. User input: The Fibonacci sequence is a series of numbers where each term is the sum of the two preceding ones. It typically starts with **0 and 1**. Here are the first 10 terms:

```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
```
"""
    reply, reasoning = api_connector.send_request(test_messages, verbose=True)
    print("Request sent successfully.")
    # pretty_json = json.dumps(reply, indent=4, ensure_ascii=False)
    print("Reply:", reply)
    print("Reasoning:", reasoning)
